import myAxios from "../plugins/myAxios";
import { getCurrentUserState, setCurrentUserState } from "../states/user";

export const getCurrentUser = async (isGetUser: string) => {
    const currentUser = getCurrentUserState();
    if (currentUser) {
        return currentUser;
    }
    // (不存在则)从远程获取,访问首页无需登录
    const res = await myAxios.get('/user/current');
    if (res.code === 0) {
        setCurrentUserState(res.data);
        return res.data;
    }

    // 未登录则跳转到登录页
    if (res.code === 40100 && isGetUser === "1") {
        const redirectUrl = window.location.href;
        window.location.replace(`/user/login?redirect=${redirectUrl}`);
    }
    return null;
}
